import tkinter as tk
from threading import Event
from tkinter import ttk, BooleanVar
from tkinter.font import Font
from files.file_ini import FileIni
from windows import root, test_mode_list, test_mode_index, testcase_refresh_loop, test_result_var, test_fail_id
from cases.case_config import CasesConfig
from windows.caselistview import CaseListView

from bases.windows.time_label import TimeLabel
from windows import test_time_bool
from windows import test_pass_loop,test_fail_loop,test_total_loop,test_rate
# 整体UI逻辑控制
class CaseMainFrame(tk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.runBtn = tk.Button(self, text='运行')
        self.runBtn.pack()

        # 1行——打开的文件路径名称      Frame：label与label
        frame_file = tk.Frame(self)
        label_file = tk.Label(frame_file, text='打开的文件路径为:')
        label_file_open = tk.Label(frame_file, text='暂定')

        label_file.pack(side='left')
        label_file_open.pack(side='left')
        frame_file.pack(side='top', fill='x')
        # 2行——用例执行方式，用例运行控制(调试)           Frame：一个下拉选择框，四个按钮
        self.frame_test_control = tk.Frame(self)
        self.test_mode_box = ttk.Combobox(self.frame_test_control, values=test_mode_list)
        self.test_mode_box.current(0)
        self.test_mode_box.pack(side='left')

        ## 选择位置————失败就复位
        print('test_mode: xx', self.test_mode_box.get())
        self.btn_pause = tk.Button(self.frame_test_control, text='暂停运行', command=lambda :print('暂停运行'))
        self.btn_continue = tk.Button(self.frame_test_control, text='继续运行', command=lambda :print('继续运行'))
        self.btn_single_run = tk.Button(self.frame_test_control, text='单步运行', command=lambda :print('单步运行'))
        self.btn_end = tk.Button(self.frame_test_control, text='终止运行', command=lambda :print('终止运行'))
        self.btn_end.pack(side='right')
        self.btn_single_run.pack(side='right')
        self.btn_continue.pack(side='right')
        self.btn_pause.pack(side='right')
        self.frame_test_control.pack(side='top', fill='x')
        # git测试
        # 3行——运行时间，运行结果，报错记录。使用grid布局,一行，比例为1:1:1
        font = Font(family='微软雅黑', size=24)
        self.frame_case = tk.Frame(self)

        # 控制测试时间的线程事件控制变量
        self.test_time_event = Event()

        self.label_time = TimeLabel(self.frame_case, self.test_time_event, test_time_bool, font=font, text='测试时间')
        # self.label_time = tk.Label(self.frame_case, font=font, text='测试时间')
        self.label_test_res = tk.Label(self.frame_case, text='测试结果',font=font, textvariable=test_result_var)
        self.label_fail_case = tk.Label(self.frame_case, text='测试FAIL项',font=font,textvariable=test_fail_id, fg='red')
        self.frame_case.columnconfigure(0, weight=1)
        self.frame_case.columnconfigure(1, weight=2)
        self.frame_case.columnconfigure(2, weight=2)

        self.label_time.grid(row=0, column=0, padx=5, pady=5,sticky="w")
        self.label_test_res.grid(row=0, column=1, padx=5, pady=5,)
        self.label_fail_case.grid(row=0, column=2, padx=5, pady=5, sticky="w")
        # self.label_time.pack(side='left')
        # self.label_test_res.pack(side='left')
        # self.label_failcase.pack(side='left')
        self.frame_case.pack(side='top', fill='x')

        # 4行——运行时，产品的SN号
        self.frame_SN = tk.Frame(self)
        self.label_SN = tk.Label(self.frame_SN, text='SN: ')
        self.label_SN_input = tk.Label(self.frame_SN, text='XXXXXXXXXXXXXXXXXXXXXXXXX')
        self.label_SN.pack(side='left')
        self.label_SN_input.pack(side='left')
        self.frame_SN.pack(side='top',fill='x')

        self.listView = CaseListView(self)
        self.listView.pack(side='top',expand=True, fill='both')

        # 逻辑
        self.runBtn.bind('<Button-1>', lambda e:self.listView.run_event())
        self.btn_pause.bind('<Button-1>', lambda e:self.listView.btn_pause_event())
        self.btn_continue.bind('<Button-1>', lambda e:self.listView.btn_continue_event())
        self.btn_single_run.bind('<Button-1>', lambda e:self.listView.btn_single_run_event())
        self.btn_end.bind('<Button-1>', lambda e:self.listView.btn_end_event())

        self.test_mode_box.bind("<<ComboboxSelected>>", self.test_mode_select)

        # 测试项
        # self.pass_loop = test_pass_loop.get()
        # self.fail_loop = test_fail_loop.get()
        # self.total_loop = test_total_loop.get()
        # self.rate = float(test_rate.get()[:-1])

        # 从文件中读取测试次数
        self.read_file_ini_test_count()
        self.bool_temp = True
        self.s_late = None
        test_result_var.trace('w', self.test_result_show)
    def read_file_ini_test_count(self):
        self.total_loop, self.pass_loop = [int(i) for i in FileIni.read_test_count()]
        self.fail_loop = self.total_loop - self.pass_loop
        if self.total_loop == 0:
            self.rate = 0.00
        else:
            self.rate = round(self.pass_loop / self.total_loop * 100, 2)
        test_pass_loop.set(self.pass_loop)
        test_fail_loop.set(self.fail_loop)
        test_total_loop.set(self.total_loop)
        test_rate.set(str(self.rate)+'%')


    def test_result_show(self, *args):
        s = test_result_var.get()

        # print('sxxxxxxxxxxxxxxxx', s)
        # input()
        if s in ('PASS','Testing'):
            self.label_test_res.config(fg='green')
        elif s == 'FAIL':
            self.label_test_res.config(fg='red')
        self.refresh_test_loop(s)
        # self.rate = round(self.pass_loop / self.total_loop * 100, 2)

    def refresh_test_loop(self, s):
        if s != self.s_late:
            self.s_late = s
            print('更新数据')
            if s == 'PASS':             # 测试通过
                self.pass_loop += 1
            elif s == 'FAIL':           # 测试失败
                self.fail_loop += 1
            else:                       # 其他测试中的结果。
                return
            self.total_loop += 1
            self.rate = round(self.pass_loop / self.total_loop * 100, 2)
            print(self.total_loop)
            test_pass_loop.set(self.pass_loop)
            test_fail_loop.set(self.fail_loop)
            test_total_loop.set(self.total_loop)
            test_rate.set(str(self.rate)+'%')
            FileIni.write_test_count(self.total_loop, self.pass_loop)


    def test_mode_select(self, event):
        # 获取选中值的下标
        selected = self.test_mode_box.get()
        index = test_mode_list.index(selected)
        test_mode_index.set(index)

if __name__ == '__main__':
    CasesConfig.case_init()  # 用例配置初始化
    mainFrame = CaseMainFrame(root,highlightbackground="grey", highlightthickness=2)
    mainFrame.pack(padx=5,pady=5,expand=True,fill='both')
    root.mainloop()